#include "frmtcpclient.h"
#include "ui_frmtcpclient.h"
#include <QTcpSocket>
#include <QTextEdit>

frmtcpclient::frmtcpclient(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::frmtcpclient),
    mainWindow(qobject_cast<frmmain*>(parent)),
    isCommandMode(false)
{
    ui->setupUi(this);

    // 设置默认值
    ui->ipLineEdit->setText("192.168.1.100");
    ui->portLineEdit->setText("8080");

    // 连接信号和槽
    if (mainWindow) {
        QTcpSocket* tcpSocket = mainWindow->getTcpSocket();
        connect(tcpSocket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, [this](QAbstractSocket::SocketError error) {
            Q_UNUSED(error); // 避免未使用参数的警告
            updateMainResponse("TCP 错误: " + mainWindow->getTcpSocket()->errorString());
            on_connectButton_clicked(); // 自动断开
        });
    }
}

frmtcpclient::~frmtcpclient()
{
    delete ui;
}

void frmtcpclient::on_connectButton_clicked()
{
    if (!mainWindow) {
        updateMainResponse("错误：主窗口指针无效");
        return;
    }

    QTcpSocket *tcpSocket = mainWindow->getTcpSocket();
    if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        tcpSocket->disconnectFromHost();
        ui->connectButton->setText("连接");
        ui->enterCommandModeButton->setEnabled(false);
        ui->exitCommandModeButton->setEnabled(false);
        enableConfigControls(false);
        mainWindow->setIsTcpConnected(false);
        updateMainResponse("TCP 已断开");
    } else {
        QString ip = ui->ipLineEdit->text().trimmed();
        QString portStr = ui->portLineEdit->text().trimmed();

        if (ip.isEmpty()) {
            updateMainResponse("错误：IP 地址不能为空");
            return;
        }

        bool ok;
        int port = portStr.toInt(&ok);
        if (!ok || port < 1 || port > 65535) {
            updateMainResponse("错误：端口号必须是 1-65535 之间的整数");
            return;
        }

        tcpSocket->connectToHost(ip, port);
        if (tcpSocket->waitForConnected(5000)) {
            ui->connectButton->setText("断开");
            ui->enterCommandModeButton->setEnabled(true);
            enableConfigControls(false);
            mainWindow->setIsTcpConnected(true);
            updateMainResponse("已连接到 " + ip + ":" + QString::number(port));
        } else {
            updateMainResponse("错误：无法连接到 " + ip + ":" + QString::number(port) + ": " + tcpSocket->errorString());
        }
    }
}

void frmtcpclient::on_enterCommandModeButton_clicked()
{
    if (!mainWindow || !mainWindow->getIsTcpConnected()) {
        updateMainResponse("错误：请先建立 TCP 连接");
        return;
    }

    sendCommandModeCommand(true);
    isCommandMode = true;
    ui->enterCommandModeButton->setEnabled(false);
    ui->exitCommandModeButton->setEnabled(true);
    enableConfigControls(true);
    updateMainResponse("已进入指令模式");
}

void frmtcpclient::on_exitCommandModeButton_clicked()
{
    if (!mainWindow || !mainWindow->getIsTcpConnected()) {
        updateMainResponse("错误：请先建立 TCP 连接");
        return;
    }

    sendCommandModeCommand(false);
    isCommandMode = false;
    ui->enterCommandModeButton->setEnabled(true);
    ui->exitCommandModeButton->setEnabled(false);
    enableConfigControls(false);
    updateMainResponse("已退出指令模式");
}

void frmtcpclient::on_applyConfigButton_clicked()
{
    if (!isCommandMode) {
        updateMainResponse("错误：请先进入指令模式");
        return;
    }

    QString nmeaMsgId = ui->nmeaMsgIdComboBox->currentText().split(" ").first();
    QString nmeaRate = ui->nmeaRateLineEdit->text().trimmed();
    QString rtcmMsgType = ui->rtcmMsgTypeLineEdit->text().trimmed();
    QString rtcmRate = ui->rtcmRateLineEdit->text().trimmed();
    bool autoMode = ui->baseStationAutoCheckBox->isChecked();
    QString lat = ui->baseStationLatLineEdit->text().trimmed();
    QString lon = ui->baseStationLonLineEdit->text().trimmed();

    QString command = QString("$CONFIG,%1,%2,%3,%4,%5,%6,%7\r\n")
                         .arg(nmeaMsgId)
                         .arg(nmeaRate)
                         .arg(rtcmMsgType)
                         .arg(rtcmRate)
                         .arg(autoMode ? "1" : "0")
                         .arg(lat)
                         .arg(lon);

    QTcpSocket *tcpSocket = mainWindow->getTcpSocket();
    if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        tcpSocket->write(command.toUtf8());
        tcpSocket->flush();
        updateMainResponse("已应用配置: " + command.trimmed());
    } else {
        updateMainResponse("错误：TCP 连接无效");
    }
}

void frmtcpclient::on_resetButton_clicked()
{
    resetConfigFields();
    enableConfigControls(false);
    if (isCommandMode) {
        sendCommandModeCommand(false);
        isCommandMode = false;
        ui->enterCommandModeButton->setEnabled(true);
        ui->exitCommandModeButton->setEnabled(false);
    }
    updateMainResponse("配置已重置");
}

void frmtcpclient::sendCommandModeCommand(bool enter)
{
    if (!mainWindow || !mainWindow->getIsTcpConnected()) return;

    QString command = enter ? "$CFG+\r\n" : "$CFG-\r\n";
    QTcpSocket *tcpSocket = mainWindow->getTcpSocket();
    if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        tcpSocket->write(command.toUtf8());
        tcpSocket->flush();
    }
}

void frmtcpclient::enableConfigControls(bool enable)
{
    ui->nmeaMsgIdComboBox->setEnabled(enable);
    ui->nmeaRateLineEdit->setEnabled(enable);
    ui->rtcmMsgTypeLineEdit->setEnabled(enable);
    ui->rtcmRateLineEdit->setEnabled(enable);
    ui->baseStationAutoCheckBox->setEnabled(enable);
    ui->baseStationLatLineEdit->setEnabled(enable);
    ui->baseStationLonLineEdit->setEnabled(enable);
    ui->applyConfigButton->setEnabled(enable);
    ui->resetButton->setEnabled(enable);
}

void frmtcpclient::resetConfigFields()
{
    ui->nmeaRateLineEdit->clear();
    ui->rtcmMsgTypeLineEdit->clear();
    ui->rtcmRateLineEdit->clear();
    ui->baseStationLatLineEdit->clear();
    ui->baseStationLonLineEdit->clear();
    ui->baseStationAutoCheckBox->setChecked(true);
}

void frmtcpclient::updateMainResponse(const QString &msg)
{
    if (mainWindow) {
        QTextEdit *responseTextEdit = mainWindow->findChild<QTextEdit*>("responseTextEdit");
        if (responseTextEdit) {
            responseTextEdit->append(msg);
        }
    }
}
